/**
 * 滚动效果增强脚本
 * 为黑蝎营销策划公司网站添加丰富的滚动动效
 */

document.addEventListener('DOMContentLoaded', function() {
  // 初始化滚动显示元素
  initScrollReveal();
  
  // 初始化视差滚动效果
  initParallaxEffect();
  
  // 初始化滚动进度指示器
  initScrollProgress();
  
  // 初始化3D卡片效果
  init3DCardEffect();
});

/**
 * 初始化滚动显示效果
 * 当元素进入视口时添加动画
 */
function initScrollReveal() {
  // 获取所有需要滚动显示的元素
  const revealElements = document.querySelectorAll('.scroll-reveal');
  
  // 创建观察器实例
  const observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        entry.target.classList.add('active');
        // 如果只需要触发一次，可以取消观察
        observer.unobserve(entry.target);
      }
    });
  }, {
    threshold: 0.1, // 当元素有10%进入视口时触发
    rootMargin: '0px 0px -50px 0px' // 提前50px触发
  });
  
  // 开始观察所有元素
  revealElements.forEach(element => {
    observer.observe(element);
  });
}

/**
 * 初始化视差滚动效果
 * 根据滚动位置移动元素
 */
function initParallaxEffect() {
  // 获取所有需要视差效果的元素
  const parallaxElements = document.querySelectorAll('.parallax');
  
  // 滚动时更新元素位置
  window.addEventListener('scroll', () => {
    const scrollTop = window.pageYOffset;
    
    parallaxElements.forEach(element => {
      const speed = element.dataset.speed || 0.5;
      const offset = scrollTop * speed;
      element.style.transform = `translateY(${offset}px)`;
    });
  });
}

/**
 * 初始化滚动进度指示器
 * 显示页面滚动进度
 */
function initScrollProgress() {
  // 创建进度条元素
  const progressBar = document.createElement('div');
  progressBar.className = 'scroll-progress-bar';
  document.body.appendChild(progressBar);
  
  // 更新进度条
  window.addEventListener('scroll', () => {
    const windowHeight = document.documentElement.scrollHeight - window.innerHeight;
    const scrolled = (window.scrollY / windowHeight) * 100;
    progressBar.style.width = `${scrolled}%`;
  });
}

/**
 * 初始化3D卡片效果
 * 根据鼠标位置旋转卡片
 */
function init3DCardEffect() {
  // 获取所有3D卡片
  const cards = document.querySelectorAll('.card-3d');
  
  cards.forEach(card => {
    // 鼠标进入卡片
    card.addEventListener('mouseenter', function(e) {
      this.style.transition = 'none';
    });
    
    // 鼠标在卡片上移动
    card.addEventListener('mousemove', function(e) {
      // 获取鼠标在卡片上的相对位置
      const rect = this.getBoundingClientRect();
      const x = e.clientX - rect.left;
      const y = e.clientY - rect.top;
      
      // 计算旋转角度（最大±15度）
      const rotateY = ((x / rect.width) * 30) - 15;
      const rotateX = (((y / rect.height) * 30) - 15) * -1;
      
      // 应用变换
      this.style.transform = `perspective(1000px) rotateX(${rotateX}deg) rotateY(${rotateY}deg)`;
    });
    
    // 鼠标离开卡片
    card.addEventListener('mouseleave', function() {
      this.style.transition = 'transform 0.5s ease';
      this.style.transform = 'perspective(1000px) rotateX(0) rotateY(0)';
    });
  });
}

/**
 * 滚动到指定元素
 * @param {string} elementId - 目标元素ID
 * @param {number} offset - 偏移量（像素）
 */
function scrollToElement(elementId, offset = 0) {
  const element = document.getElementById(elementId);
  if (!element) return;
  
  const elementPosition = element.getBoundingClientRect().top + window.pageYOffset;
  const offsetPosition = elementPosition - offset;
  
  window.scrollTo({
    top: offsetPosition,
    behavior: 'smooth'
  });
}

/**
 * 添加滚动触发动画
 * 当滚动到特定位置时触发动画
 */
window.addEventListener('scroll', function() {
  const scrollPosition = window.scrollY;
  
  // 添加视差滚动效果
  document.querySelectorAll('.section-title').forEach(title => {
    const titlePosition = title.offsetTop;
    const windowHeight = window.innerHeight;
    
    if (scrollPosition > titlePosition - windowHeight + 100) {
      title.classList.add('animated');
    }
  });
  
  // 数字计数器动画
  if (document.querySelector('.counter-section')) {
    const counterSection = document.querySelector('.counter-section');
    const counterPosition = counterSection.offsetTop;
    
    if (scrollPosition > counterPosition - window.innerHeight + 200 && !counterSection.classList.contains('counted')) {
      counterSection.classList.add('counted');
      
      document.querySelectorAll('.counter').forEach(counter => {
        const target = parseInt(counter.getAttribute('data-target'));
        const duration = 2000; // 动画持续时间（毫秒）
        const step = target / (duration / 16); // 假设60fps，每帧增加的值
        
        let current = 0;
        const updateCounter = () => {
          if (current < target) {
            current += step;
            counter.textContent = Math.floor(current);
            requestAnimationFrame(updateCounter);
          } else {
            counter.textContent = target;
          }
        };
        
        updateCounter();
      });
    }
  }
});

// 添加滚动到顶部按钮
function addScrollToTopButton() {
  const button = document.createElement('button');
  button.innerHTML = '<i class="fas fa-arrow-up"></i>';
  button.className = 'scroll-to-top';
  document.body.appendChild(button);
  
  window.addEventListener('scroll', function() {
    if (window.scrollY > 300) {
      button.classList.add('visible');
    } else {
      button.classList.remove('visible');
    }
  });
  
  button.addEventListener('click', function() {
    window.scrollTo({
      top: 0,
      behavior: 'smooth'
    });
  });
}

// 页面加载完成后添加滚动到顶部按钮
window.addEventListener('load', addScrollToTopButton);

// 为公司简介部分添加鼠标悬停3D效果
document.addEventListener('DOMContentLoaded', function() {
  const aboutSection = document.querySelector('.about-section');
  if (aboutSection) {
    aboutSection.addEventListener('mousemove', function(e) {
      const cards = this.querySelectorAll('.auto-scroll-item');
      const rect = this.getBoundingClientRect();
      const x = e.clientX - rect.left;
      const y = e.clientY - rect.top;
      
      cards.forEach(card => {
        // 计算卡片中心到鼠标的距离
        const cardRect = card.getBoundingClientRect();
        const cardX = (cardRect.left + cardRect.right) / 2 - e.clientX;
        const cardY = (cardRect.top + cardRect.bottom) / 2 - e.clientY;
        const distance = Math.sqrt(cardX * cardX + cardY * cardY);
        const maxDistance = Math.sqrt(rect.width * rect.width + rect.height * rect.height) / 2;
        
        // 根据距离计算旋转角度和阴影
        const rotateX = (cardY / maxDistance) * 5; // 最大旋转5度
        const rotateY = (cardX / maxDistance) * -5;
        const shadowX = (cardX / maxDistance) * 10;
        const shadowY = (cardY / maxDistance) * 10;
        
        // 应用变换
        card.style.transform = `perspective(1000px) rotateX(${rotateX}deg) rotateY(${rotateY}deg)`;
        card.style.boxShadow = `${shadowX}px ${shadowY}px 20px rgba(0,0,0,0.1)`;
      });
    });
    
    // 鼠标离开时重置效果
    aboutSection.addEventListener('mouseleave', function() {
      const cards = this.querySelectorAll('.auto-scroll-item');
      cards.forEach(card => {
        card.style.transform = 'perspective(1000px) rotateX(0) rotateY(0)';
        card.style.boxShadow = '0 5px 15px rgba(0,0,0,0.08)';
        card.style.transition = 'all 0.5s ease';
      });
    });
  }
});